var express = require("express");
var router = express.Router();
let { pay, paylist, dong, paylist1,visitor } = require("../models/model");
//支付宝支付
const AlipayFormData = require('alipay-sdk/lib/form').default
const alipaySdk = require('../alipaySdk/alipay')
//缴费分类类型
router.get('/pay', async (req, res) => {
    let data = await pay.find();
    res.send({
        code: 200,
        data
    })
})
//获取个人缴费记录
router.get('/paylist', async (req, res) => {
    let data = await paylist.find({ userid: '672b2881562e11de35cc4ca4' }).populate('rommid').populate('userid');
    console.log(data,'data2')
    let data1 = await dong.findOne({ _id:data[0].rommid.cid})
    console.log(data1.name,'data1')
    res.send({
        code: 200,
        data,
        data1
    })
})
//支付宝支付
router.post('/pcpay', async (req, res) => {
    //价钱
    let price = req.body.payable;
    await paylist1.create({
        name: '67275d88a92cf6a82a1e3b67',
        time: new Date(),
        price:price,
        title:'物业费'
    })
    let status=!req.body.status;
    let id=req.body._id;
    console.log(status,id,'status')
    await paylist.updateOne({_id:id},{status:status})
    //订单号
    let time= Math.floor(new Date().getTime());
    // console.log(time,'time')
    const formData = new AlipayFormData()
    formData.setMethod('get');
    // 通过addField增加参数
    // 在用户支付完成之后，支付宝服务器会根据传入的notify_url,以post请求的形式将支付结果作为参数通知到商户系统
    // 支付成功或失败都返回
    formData.addField('returnUrl', "http://localhost:5173/list3");
    formData.addField('bizContent', {
        out_trade_no: time,//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
        product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
        total_amount: price,// 订单总金额
        subject: '物业费',// 订单描述
        body: '34234',// 商品描述
    }) 
    // 返回promise
    const result = await alipaySdk.exec(
        'alipay.trade.wap.pay',//统一收单下单并支付页面接口, 'alipay.trade.page.pay'(pc端的支付接口)
        {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
        { formData: formData }// result为可以跳转支付链接的url
    )
    res.send({
        code: 200,
        result
    })
})
//交完费用记录
router.get('/paylist1',async(req,res)=>{
    let data=await paylist1.find()
    // console.log(data,'2222222222222222222222222')
    res.send({
        code:200,
        data
    })    
})
//邀请访客
router.post('/visitor',async(req,res)=>{
    let a=req.body
    await visitor.create({
        name:a.name,
        gender:a.gender,
        phone:a.phone,
        time:a.time,
        status:true,
        rommid:a.rommid,
        userid:a.userid,
        duration:a.duration,
    })
    res.send({
        code:200,
        msg:'添加成功'
    })
})
module.exports = router;